﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SAIN
{
    public class ExceptionsLogger
    {
        public static void WriteLog(Exception ex)
        {
            try
            {
                string Message = string.Empty;
                Message = ExceptionsLogger.AddHeader(Message);

                if (ex != null)
                {
                    Message = Message + "\n\n+" + ex.Message;
                    Message = Message + "\n\n -Source: " + ex.Source;
                    Message = Message + "\n\n -StackTrace: " + ex.StackTrace;
                    Message = Message + "\n\n -TargetSite: " + ex.TargetSite.ToString();

                    if (ex.InnerException != null)
                    {
                        Message += ExceptionsLogger.ExceptionStringBuilder(ex.InnerException);
                    }
                }
                string ErrorLogFile = string.IsNullOrEmpty(Config.GetKey("ErrorLogFile")) ?
                    @"C:\ErrorLogFile.txt" : Config.GetKey("ErrorLogFile");


                System.IO.File.AppendAllText(ErrorLogFile, Message,System.Text.Encoding.Unicode);
            }
            catch { }
        }
        public static string ExceptionStringBuilder(Exception ex)
        {
            string Message = ex.Message;
            Message = Message + "\n\n -Source: " + ex.Source;
            Message = Message + "\n\n -StackTrace: " + ex.StackTrace;
            Message = Message + "\n\n -TargetSite: " + ex.TargetSite;
            if (ex.InnerException != null)
            {
                Message += ExceptionsLogger.ExceptionStringBuilder(ex.InnerException);
            }
            return Message;
        }
        public static string AddHeader(string message)
        {
            return message + "\n\n -An exception was occurred on SAIN at "
                + DateTime.Now.ToString("yyyy/MM/dd") + " at " + DateTime.Now.ToShortTimeString() + "\n\n";
        }
    }
}